1. Home
  2. Node.js
  3. Node.js Basics
  4. Node.js – Hello World Example

Node.js – Hello World Example

You can run Node.js application an console based or web-based application. Console based application will run your system terminal and a web-based application will use an inbuilt web server to make an application accessible on the web browser.

Console-based Hello World Example

Use the Node.js console module to print output on your system console. Create a JavaScript file nodejs_hello_console.js using the below content.

Execute your script using the node

node nodejs_hello_console.js

[output]
Hello World!

Web-based Hello World Example

A Node.js web application is build with 3 parts.

  • Import module to create web server
  • Create a web server
  • Read client requests and send reponse back to client

Below is the sample application uses http module. http module creates a web server similar to Apache or Nginx web servers. Now create a server with specified host and port. Use used 0.0.0.0 host address means it will listen on all interfaces attached to the system.

Create a JavaScript file nodejs_hello_web.js and add the following content.

Execute the script using node. It will start a web server on specified port and host.

node nodejs_hello_web.js

[output]
Web server running at http://0.0.0.0:3000

For example, above script started a web server on port 3000. Visit your server on a defined port in the web browser. It will show you the result like below.

Tags , , ,